/**
 * 收银系统主界面
 */
Ext.define("PSI.Pos.MainForm", {
	extend : 'Ext.window.Window',

	modal : true,
	closable : false,
	maximized : true,
	width : 400,
	layout : "border",

	initComponent : function() {
		var me = this;

		Ext.apply(me, {
					header : {
						title : "<span style='font-size:120%'>收银系统 </span>",
						iconCls : "PSI-fid2039",
						height : 40
					},
					height : 240,
					items : [{
								region : "north",
								height : 60,
								layout : "border",
								border : 0,
								items : [{
											region : "center",
											layout : "fit",
											border : 0,
											items : [{
														xtype : "hidden",
														id : "editId"
													}, {
														xtype : "hidden",
														id : "editShopId"
													}, {
														border : 0,
														id : "editShopName"
													}]
										}, {
											region : "east",
											width : 200,
											broder : 0,
											xtype : "container",
											items : [{
														xtype : "button",
														id : "buttonChangeShop",
														html : "<h2>切换店铺</h2>",
														height : 60,
														width : 90,
														handler : me.onChangeShop,
														scope : me
													}, {
														xtype : "button",
														html : "<h2>开新单</h2>",
														margin : "0, 0, 0 10",
														height : 60,
														width : 90,
														handler : me.newBill,
														scope : me
													}]
										}]
							}, {
								region : "center",
								layout : "border",
								items : [{
											region : "center",
											layout : "fit",
											items : [me.getGoodsArea()]
										}, {
											region : "east",
											width : 300,
											layout : "fit",
											items : [me.getScanCodeArea()]
										}]
							}, {
								region : "south",
								height : 100,
								html : me.getHelpHtml()
							}],
					listeners : {
						show : {
							fn : me.onWndShow,
							scope : me
						}
					}
				});

		me.callParent(arguments);

		Ext.create("Ext.util.KeyMap", {
					target : window,
					binding : [{
								key : Ext.EventObject.ONE,
								alt : true,
								fn : function() {
									Ext.getCmp("editCustomerInput").focus();
								}
							}, {
								key : Ext.EventObject.THREE,
								alt : true,
								fn : function() {
									Ext.getCmp("editCodeInput").focus();
								}
							}, {
								key : Ext.EventObject.FIVE,
								alt : true,
								fn : function() {
									Ext.getCmp("editTakeMoney").focus();
								}
							}, {
								key : Ext.EventObject.X,
								alt : true,
								fn : function() {
									var store = me.getGoodsGrid().getStore();
									var cnt = store.getCount();
									if (cnt > 0) {
										store.removeAt(cnt - 1);
										me.calAllMoney();
										me.calcChange();
									}
								}
							}, {
								key : Ext.EventObject.NINE,
								alt : true,
								fn : me.onEndTakeMoney,
								scope : me
							}, {
								key : Ext.EventObject.N,
								alt : true,
								fn : me.newBill,
								scope : me
							}, {
								key : Ext.EventObject.P,
								alt : true,
								fn : function() {
									if (me.__lastBillId) {
										me.printPosBill(me.__lastBillId);
									}
								},
								scope : me
							}]

				});
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndShow : function() {
		var me = this;
		Ext.get(window).on('beforeunload', me.onWindowBeforeUnload);

		Ext.getCmp("editCodeInput").focus();

		var me = this;
		var el = me.getEl() || Ext.getBody();
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL + "Home/Pos/shopInfo",
					params : {},
					method : "POST",
					callback : function(options, success, response) {
						el.unmask();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);
							me.setShopInfo(data);
						} else {
							PSI.MsgBox.showInfo("网络错误")
						}
					}
				});
	},

	setCurrentShopInfo : function(shop) {
		Ext.getCmp("editShopId").setValue(shop.id);
		var info = "<h1>&nbsp;" + Ext.String.htmlEncode(shop.name) + "</h1>";
		Ext.getCmp("editShopName").getEl().setHTML(info);
	},

	setShopInfo : function(data) {
		var me = this;

		if (data.length == 0) {
			PSI.MsgBox.showInfo("没有店铺启用收银系统", function() {
						Ext.get(window).un('beforeunload',
								me.onWindowBeforeUnload);
						location.replace(PSI.Const.BASE_URL);
					});
			return;
		}

		if (data.length == 1) {
			var shop = data[0];
			me.setCurrentShopInfo(shop);
			Ext.getCmp("buttonChangeShop").setDisabled(true);
			return;
		}

		// 有多个店铺，弹出窗体选择
		me.__shopDataList = data;
		me.selectShop(data);
	},

	getScanCodeArea : function() {
		var me = this;

		return {
			border : 0,
			xtype : "container",
			layout : {
				type : "table",
				columns : 1
			},
			height : "100%",
			items : [{
						id : "editCodeInput",
						xtype : "textfield",
						fieldLabel : "条码",
						labelWidth : 80,
						labelAlign : "right",
						labelSeparator : "",
						margin : 5,
						width : 280,
						fieldStyle : "font-size:250%;",
						labelStyle : "font-size:300%;margin-top:20px;",
						height : 50,
						listeners : {
							specialkey : {
								fn : me.onEditCodeSpecialKey,
								scope : me
							}
						}
					}, {
						id : "editAllMoney",
						xtype : "textfield",
						fieldLabel : "总计",
						labelWidth : 80,
						labelAlign : "right",
						labelSeparator : "",
						margin : 5,
						width : 280,
						fieldStyle : "font-size:250%;color:red;text-align:right",
						labelStyle : "font-size:300%;margin-top:20px;",
						height : 50,
						value : "0.00",
						readOnly : true
					}, {
						id : "editTakeMoney",
						xtype : "numberfield",
						hideTrigger : true,
						fieldLabel : "收款",
						labelWidth : 80,
						labelAlign : "right",
						labelSeparator : "",
						margin : 5,
						width : 280,
						fieldStyle : "font-size:250%;text-align:right",
						labelStyle : "font-size:300%;margin-top:20px;",
						height : 50,
						listeners : {
							change : {
								fn : me.onTakeMoneyChange,
								scope : me
							}
						}
					}, {
						id : "editChange",
						xtype : "textfield",
						fieldLabel : "找零",
						labelWidth : 80,
						labelAlign : "right",
						labelSeparator : "",
						margin : 5,
						width : 280,
						fieldStyle : "font-size:250%;color:red;text-align:right",
						labelStyle : "font-size:300%;margin-top:20px;",
						height : 50,
						value : "0.00",
						readOnly : true
					}]
		};
	},

	selectShop : function(data) {
		var me = this;
		var form = Ext.create("PSI.Pos.SelectShopForm", {
					parentForm : me,
					shopData : data
				});
		form.show();
	},

	onChangeShop : function() {
		var me = this;
		var form = Ext.create("PSI.Pos.SelectShopForm", {
					parentForm : me,
					shopData : me.__shopDataList
				});
		form.show();
	},

	getGoodsGrid : function() {
		var me = this;
		if (me.__goodsGrid) {
			return me.__goodsGrid;
		}

		var modelName = "PSIPosGoods";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["goodsId", "goodsCode", "goodsName", "goodsSpec",
							"unitName", "goodsCount", "goodsMoney",
							"goodsPrice"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__goodsGrid = Ext.create("Ext.grid.Panel", {
					title : "销售商品明细",
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					columns : [Ext.create("Ext.grid.RowNumberer", {
										text : "序号",
										width : 40
									}), {
								header : "商品编码",
								dataIndex : "goodsCode",
								menuDisabled : true,
								sortable : false,
								width : 120
							}, {
								header : "商品名称",
								dataIndex : "goodsName",
								menuDisabled : true,
								sortable : false,
								width : 200
							}, {
								header : "规格型号",
								dataIndex : "goodsSpec",
								menuDisabled : true,
								sortable : false,
								width : 200
							}, {
								header : "销售数量",
								dataIndex : "goodsCount",
								menuDisabled : true,
								sortable : false,
								align : "right"
							}, {
								header : "单位",
								dataIndex : "unitName",
								menuDisabled : true,
								sortable : false,
								width : 60
							}, {
								header : "销售单价",
								dataIndex : "goodsPrice",
								menuDisabled : true,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 150
							}, {
								header : "销售金额",
								dataIndex : "goodsMoney",
								menuDisabled : true,
								sortable : false,
								align : "right",
								xtype : "numbercolumn",
								width : 150
							}],
					store : store
				});

		return me.__goodsGrid;
	},

	getGoodsArea : function() {
		var me = this;

		return {
			layout : "border",
			items : [{
						region : "north",
						height : 40,
						items : [{
									id : "editCustomerInput",
									xtype : "psi_customerfield",
									labelAlign : "right",
									labelSeparator : "",
									labelWidth : 40,
									margin : "5, 0, 0, 0",
									fieldLabel : "客户",
									width : 300
								}]
					}, {
						region : "center",
						layout : "fit",
						items : [me.getGoodsGrid()]
					}]
		};
	},

	getHelpHtml : function() {
		var info = "<div style='font-size:200%'>快捷键说明</div>";
		info += "<span style='font-size:200%'>Alt + 1 - 选择客户</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<span style='font-size:200%'>Alt + 3 - 扫码</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<span style='font-size:200%'>Alt + 5 - 开始收款</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<span style='font-size:200%'>Alt + 9 - 收款完毕</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<br /><span style='font-size:200%'>Alt + N - 开新单</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<span style='font-size:200%'>Alt + X - 删除最后一条商品</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		info += "<span style='font-size:200%'>Alt + P - 重新打印</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

		return info;
	},

	onEditCodeSpecialKey : function(field, e) {
		var me = this;

		if (e.getKey() == e.ENTER) {
			var barcode = Ext.getCmp("editCodeInput").getValue();
			if (!barcode) {
				return;
			}

			var grid = me.getGoodsGrid();
			var el = grid.getEl() || Ext.getBody();
			el.mask(PSI.Const.LOADING);
			var r = {
				url : PSI.Const.BASE_URL + "Home/Pos/goodsByBarcode",
				params : {
					barcode : barcode
				},
				method : "POST",
				callback : function(options, success, response) {
					el.unmask();
					if (success) {
						var data = Ext.JSON.decode(response.responseText);
						me.setGoodsInfo(barcode, data);
					}
				}
			};
			Ext.Ajax.request(r);
		}
	},

	calAllMoney : function() {
		var me = this;

		var allMoney = 0;
		var store = me.getGoodsGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			allMoney += parseFloat(item.get("goodsMoney"));
		}

		var m = Ext.util.Format.number(allMoney, "0,0.00");
		Ext.getCmp("editAllMoney").setValue(m);
	},

	setGoodsInfo : function(barcode, data) {
		var me = this;

		if (data.length == 0) {
			PSI.MsgBox.showInfo("条码为[" + barcode + "]的商品不存在", function() {
						Ext.getCmp("editCodeInput").focus();
					});
			return;
		}

		if (data.length == 1) {
			var goods = data[0];
			goods.goodsCount = 1;
			goods.goodsMoney = goods.goodsPrice;

			var store = me.getGoodsGrid().getStore();
			store.add(goods);

			Ext.getCmp("editCodeInput").setValue(null);

			me.calAllMoney();
			me.calcChange();
			return;
		}

		// 一个条码对应多个商品，弹出窗体供用户选择
		var form = Ext.create("PSI.Pos.SelectGoodsForm", {
					parentForm : me,
					goodsData : data
				});
		form.show();
	},

	afterSelectGoodsFormClosed : function() {
		var editCodeInput = Ext.getCmp("editCodeInput");
		editCodeInput.setValue(null);
		editCodeInput.focus();
	},

	calcChange : function() {
		var editAllMoney = Ext.getCmp("editAllMoney");
		var editTakeMoney = Ext.getCmp("editTakeMoney");
		var editChange = Ext.getCmp("editChange");

		var c = parseFloat(editTakeMoney.getValue())
				- parseFloat(editAllMoney.getValue());
		if (isNaN(c)) {
			c = 0;
		}
		var m = Ext.util.Format.number(c, "0,0.00");;
		editChange.setValue(m);

	},

	onTakeMoneyChange : function() {
		var me = this;
		me.calcChange();
	},

	getSaveData : function(commit) {
		var me = this;

		var result = {
			id : Ext.getCmp("editId").getValue(),
			shopId : Ext.getCmp("editShopId").getValue(),
			customerId : Ext.getCmp("editCustomerInput").getIdValue(),
			saleMoney : Ext.getCmp("editAllMoney").getValue(),
			totalPay : Ext.getCmp("editTakeMoney").getValue(),
			returnMoney : Ext.getCmp("editChange").getValue(),
			commit : commit,
			items : []
		};

		var store = me.getGoodsGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			result.items.push({
						goodsId : item.get("goodsId"),
						goodsCount : item.get("goodsCount"),
						goodsPrice : item.get("goodsPrice")
					});
		}

		return Ext.JSON.encode(result);
	},

	onEndTakeMoney : function() {
		var me = this;

		var store = me.getGoodsGrid().getStore();
		if (store.getCount() == 0) {
			PSI.MsgBox.showInfo("没有录入商品明细", function() {
						Ext.getCmp("editCodeInput").focus();
					});
			return;
		}

		var takeMoney = Ext.getCmp("editTakeMoney").getValue();
		if (takeMoney == null) {
			PSI.MsgBox.showInfo("没有收款", function() {
						Ext.getCmp("editTakeMoney").focus();
					});
			return;
		}

		var change = parseFloat(Ext.getCmp("editChange").getValue());
		if (change < 0) {
			PSI.MsgBox.showInfo("收款金额不够", function() {
						Ext.getCmp("editTakeMoney").focus();
					});
			return;
		}

		var el = Ext.getBody();
		el.mask(PSI.Const.LOADING);
		var r = {
			url : PSI.Const.BASE_URL + "Home/Pos/commitBill",
			params : {
				jsonStr : me.getSaveData(true)
			},
			method : "POST",
			callback : function(options, success, response) {
				el.unmask();
				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					if (data.success) {
						PSI.MsgBox.tip("成功完成收款");
						me.__lastBillId = data.id;
						me.printPosBill(data.id);
						me.newBill();
					} else {
						PSI.MsgBox.showInfo(data.msg);
					}
				} else {
					PSI.MsgBox.showInfo("网络错误");
				}
			}
		};
		Ext.Ajax.request(r);
	},

	newBill : function() {
		var me = this;
		var store = me.getGoodsGrid().getStore();
		store.removeAll();

		var editCustomer = Ext.getCmp("editCustomerInput");
		editCustomer.setValue(null);
		editCustomer.setIdValue(null);

		Ext.getCmp("editAllMoney").setValue("0.00");
		Ext.getCmp("editTakeMoney").setValue(null);
		Ext.getCmp("editChange").setValue("0.00");

		Ext.getCmp("editCodeInput").focus();
	},

	printPosBill : function(id) {
		var me = this;
		var el = Ext.getBody();
		el.mask("数据加载中...");
		var r = {
			url : PSI.Const.BASE_URL + "Home/Pos/getPrintBillData",
			method : "POST",
			params : {
				id : id
			},
			callback : function(options, success, response) {
				el.unmask();

				if (success) {
					var data = response.responseText;
					me.__printPosBill(data);
				}
			}
		};
		Ext.Ajax.request(r);
	},

	__printPosBill : function(data) {
		var me = this;

		var lodop = getLodop();
		if (!lodop) {
			PSI.MsgBox.showInfo("Lodop打印控件没有正确安装");
			return;
		}

		lodop.PRINT_INIT("PSI - POS");
		lodop.SET_PRINT_PAGESIZE(1, "55mm", "100mm", "POS");
		lodop.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", data);
		var result = lodop.PRINT();
	}
});